package service

import (
	"errors"
	"fmt"
	"gin-zc/dto"

	"gin-zc/model"
	"gin-zc/repository"
	"gin-zc/util"

	"golang.org/x/net/context"
)

// UserService 用户业务服务
type UserService struct{}

// Register 注册业务逻辑
func (s *UserService) Register(username, email, password string) (*model.User, error) {
	// 1. 检查用户名/邮箱是否已存在
	var existingUser model.User
	if err := repository.DB.Where("user_name = ?", username).First(&existingUser).Error; err == nil {
		return nil, errors.New("username already exists")
	}
	if err := repository.DB.Where("email = ?", email).First(&existingUser).Error; err == nil {
		return nil, errors.New("email already exists")
	}

	// 2. 密码哈希
	hashPassword, err := util.HashPassword(password)
	if err != nil {
		return nil, err
	}

	// 3. 创建用户
	user := &model.User{
		UserName: username,
		Phone:    email,
		Password: hashPassword,
	}
	if err := repository.DB.Create(user).Error; err != nil {
		return nil, err
	}

	return user, nil
}

// Login 登录业务逻辑
func (s *UserService) Login(phone, password string) (*model.User, error) {
	// 1. 查询用户
	var user model.User
	if err := repository.DB.Where("phone = ?", phone).First(&user).Error; err != nil {
		return nil, errors.New("用户不存在")
	}

	// 2. 验证密码
	if !util.VerifyMD5(password, user.Password) {
		return nil, errors.New("用户名或密码不正确")
	}

	return &user, nil
}

// GetUserByID 根据ID查询用户
func (s *UserService) GetUserByID(userID string) (*model.User, error) {
	var user model.User
	if err := repository.DB.First(&user, userID).Error; err != nil {
		return nil, errors.New("user not found")
	}
	return &user, nil
}

func (s *UserService) GetUser(ctx context.Context, userID string) (*model.User, error) {
	var user model.User
	// 使用带log_id的context调用GORM
	if err := repository.DB.WithContext(ctx).First(&user, userID).Error; err != nil {
		return nil, err
	}
	// 验证：从ctx中提取log_id（调试用）
	logID, ok := ctx.Value("log_id").(string)
	if !ok {
		fmt.Println("服务层中context无log_id")
	} else {
		fmt.Printf("服务层传入GORM的log_id: %s\n", logID)
	}
	return &user, nil
}

// 查用户及其所有订单
func (s *UserService) GetUserWithOrders(ctx context.Context, userID string) (*model.User, error) {
	var user model.User
	// 预加载Orders关联
	if err := repository.DB.Preload("Orders").First(&user, userID).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

// 查订单及其用户（反向查询）
func GetOrderWithUser(OrderId uint) (*model.Order, error) {
	var order model.Order
	// 预加载User关联（文章的作者）
	if err := repository.DB.Preload("User").First(&order, OrderId).Error; err != nil {
		return nil, err
	}
	return &order, nil
}

// GetUserDTO 根据ID查询用户，并转换为DTO
func (s *UserService) GetUserDTO(ctx context.Context, userID string) (*dto.UserDTO, error) {
	// 1. 查询数据库模型
	var user model.User
	if err := repository.DB.WithContext(ctx).First(&user, userID).Error; err != nil {
		return nil, err
	}

	// 2. 转换为DTO（手动映射字段）
	userDTO := dto.UserDTO{
		ID:        user.ID,
		UserName:  user.UserName,
		Phone:     user.Phone,
		CreatedAt: user.CreatedAt,
	}

	return &userDTO, nil
}
